<template>
  <div class="container">
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="动态标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入动态标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="动态类型">
          <el-input
            v-model="searchForm.type"
            placeholder="请输入动态类型"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box clearfix">
      <div class="button-box clearfix">
        <el-button type="primary" @click="handleAdd">添加动态</el-button>
        <el-button type="primary" @click="handleDeleteList">批量删除</el-button>
      </div>
      <el-table
        border
        :data="dynamicList"
        style="width: 100%; min-height: 400px"
        @selection-change="handleSelectionChange"
        height="400"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="动态ID" width="120" />
        <el-table-column prop="title" label="动态标题" width="180" />
        <el-table-column prop="image" label="动态主图" width="120">
          <template slot-scope="scope">
            <img
              :src="scope.row.image"
              class="product-image"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="动态内容" width="300" />
        <el-table-column prop="type" label="动态类型" width="120" />
        <el-table-column prop="favorite_count" label="收藏数" width="120" />
        <el-table-column prop="comment_count" label="评论数" width="120" />
        <el-table-column prop="publish_time" label="发布时间" width="180" />
        <el-table-column
          label="操作"
          align="center"
          show-overflow-tooltip
          width="250"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 抽屉组件 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      size="40%"
      :before-close="handleClose"
      style="overflow-y: auto"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="动态主图" prop="image">
          <img v-if="isView && form.image" :src="form.image" class="avatar" />
          <el-upload
            v-else
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :on-error="handleError"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="beforeAvatarUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <i class="el-icon-plus avatar-uploader-icon position"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="动态标题" prop="title">
          <el-input v-model="form.title" :disabled="isView"></el-input>
        </el-form-item>

        <el-form-item label="动态类型" prop="type">
          <el-input v-model="form.type" :disabled="isView"></el-input>
        </el-form-item>
        <el-form-item label="动态内容" prop="content">
          <div
            v-if="isView"
            style="width: 100%; height: 300px; border: 1px solid #ccc"
            v-html="form.content"
          ></div>
          <Editor v-else v-model="form.content"></Editor>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isView" @click="handleClose">取消</el-button>
          <el-button v-if="!isView" type="primary" @click="submitForm('form')"
            >确定</el-button
          >
          <el-button @click="handleClose">关闭</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Editor from "@/components/Editor";

export default {
  name: "DynamicManagement",
  components: {
    Editor,
  },
  data() {
    return {
      searchForm: {
        title: "",
        type: "",
      },
      dynamicList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      form: {
        id: "",
        title: "",
        image: "",
        content: "",
        type: "",
        favorite_count: 0,
        comment_count: 0,
        publish_time: "",
      },
      drawerTitle: "添加动态",
      drawerVisible: false,
      isView: false,
      rules: {
        title: [{ required: true, message: "请输入动态标题", trigger: "blur" }],
        image: [
          { required: true, message: "请上传动态主图", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入动态内容", trigger: "blur" },
        ],
        type: [{ required: true, message: "请输入动态类型", trigger: "blur" }],
      },
      multipleSelection: [],
    };
  },
  computed: {
    ...mapGetters(["tableColumnLabels"]),
  },
  created() {
    this.fetchDynamicList();
  },
  methods: {
    fetchDynamicList() {
      // 模拟异步请求
      let res = {
        data: [
          {
            id: 1,
            title: "示例动态",
            image: "https://example.com/dynamic1.jpg",
            content: "这是一个示例动态的详细内容",
            type: "活动动态",
            favorite_count: 50,
            comment_count: 20,
            publish_time: "2025-06-01 10:21:48",
          },
        ],
      };
      this.dynamicList = res.data;
      this.total = res.data.length;
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchDynamicList();
    },
    resetSearch() {
      this.searchForm = {
        title: "",
        type: "",
      };
      this.fetchDynamicList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchDynamicList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchDynamicList();
    },
    handleAdd() {
      this.isView = false;
      this.drawerTitle = "添加动态";
      this.form = {
        id: "",
        title: "",
        image: "",
        content: "",
        type: "",
        favorite_count: 0,
        comment_count: 0,
        publish_time: "",
      };
      this.drawerVisible = true;
    },
    handleView(row) {
      this.isView = true;
      this.drawerTitle = "查看动态";
      this.form = { ...row };
      this.drawerVisible = true;
    },
    handleEdit(row) {
      this.isView = false;
      this.drawerTitle = "编辑动态";
      this.form = { ...row };
      this.drawerVisible = true;
    },
    handleDelete(row) {
      // 删除逻辑
      // 模拟删除
      this.$confirm("确定要删除该动态吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$message({
          type: "success",
          message: "动态删除成功！",
        });
        this.fetchDynamicList();
      });
    },
    handleClose() {
      this.drawerVisible = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.drawerTitle === "添加动态") {
            // 处理添加逻辑
            console.log("添加动态", this.form);
          } else if (this.drawerTitle === "编辑动态") {
            // 处理编辑逻辑
            console.log("编辑动态", this.form);
          }
          this.drawerVisible = false;
          this.fetchDynamicList();
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    async handleAvatarSuccess(res) {
      this.form.image = process.env.VUE_APP_PROXY_NETWORK_TARGET + res.data.url;
      return this.$message.success({
        title: "成功",
        message: "文件上传成功",
        duration: 2000,
      });
    },
    beforeAvatarUpload(file) {
      this.file = file;
      setTimeout(() => {
        this.submitFile();
      }, 500);
    },
    async submitFile() {
      const formData = new FormData();
      formData.append("image", this.file.raw);

      // 模拟上传成功
      // await uploadAvatar(formData).then((res) => {
      //   this.form.image = process.env.VUE_APP_PROXY_NETWORK_TARGET + res.data.url;
      // });
      this.form.image = "https://example.com/uploaded_dynamic.jpg";
    },
    handleError() {
      return this.$message.error({
        title: "上传失败",
        message: "文件上传失败",
        duration: 3000,
      });
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    handleDeleteList() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择需要删除的动态");
        return;
      }
      this.$confirm("确定要删除选中的动态吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          console.log("批量删除动态 ID:", ids);
          this.$message.success("批量删除成功");
          this.fetchDynamicList();
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-box {
  .el-table {
    margin-bottom: 20px;
  }
}

.avatar-uploader {
  width: 130px;
  height: 130px;
}
::v-deep .avatar-uploader .el-upload {
  width: 130px;
  height: 130px;
  border: 1px dashed #333333;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  position: relative;
  width: 130px;
  height: 130px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 130px;
  height: 130px;
  display: block;
}
.position {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -68%);
}
.product-image {
  border-radius: 4px;
}
</style>
